package com.laikan.reader.bookfriend.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.laikan.library.components.BasicApplication;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.BookFileUtils;
import com.laikan.reader.core.utils.FileUtil;
import com.laikan.reader.core.utils.PublicUtil;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 设置页面，退出功能 需要把各第三方登录数据清除
 *
 * @author wxl
 */
public class SettingActivity extends BasicActivity implements OnClickListener {

    File bookCachePath = PublicUtil.getFile(BookFileUtils.BOOKCONTENTPATH);
    private RelativeLayout answer_lin, cache_lin;
    private ImageView notice_switcher_img;
    Drawable drawable_back_tv, drawable_jiantou;
    private ImageView back_tv, answer_right_jiantou, iv_clearcache_loading;
    private RelativeLayout back_layout;
    private TextView tv_book_cache;
    private AnimationDrawable mClearCacheAnimationDrawable;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    showCacheStatus(false);
                    tv_book_cache.setText((String)msg.obj);
                    break;
                default:
                    break;
            }
        }
    };
    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_setting);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        answer_lin = (RelativeLayout)findViewById(R.id.answer_lin);
        notice_switcher_img = (ImageView)findViewById(R.id.notice_switcher_img);
        answer_right_jiantou = (ImageView)findViewById(R.id.answer_right_jiantou);
        cache_lin = (RelativeLayout)findViewById(R.id.cache_lin);
        tv_book_cache = (TextView)findViewById(R.id.tv_book_cache);
        iv_clearcache_loading = (ImageView)findViewById(R.id.iv_clearcache_loading);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void initData() {
        if (SPUtil.getBoolean("tongzhi_click", true)) {
            notice_switcher_img.setBackgroundResource(R.drawable.lk_setting_kai);
        }else {
            notice_switcher_img.setBackgroundResource(R.drawable.lk_setting_guan);
        }
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
        drawable_jiantou = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_enter_small), Color.parseColor("#cccccc")));
        answer_right_jiantou.setImageDrawable(drawable_jiantou);
        setCacheText();
        mClearCacheAnimationDrawable = (AnimationDrawable)iv_clearcache_loading.getBackground();
    }

    private void setCacheText() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    String cacheSize = BookFileUtils.getCacheSize(bookCachePath);
                    Message msg = handler.obtainMessage();
                    msg.obj = cacheSize;
                    handler.sendMessageAtTime(msg, 0);
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    @Override
    protected void setListener() {
        back_layout.setOnClickListener(this);
        answer_lin.setOnClickListener(this);
        notice_switcher_img.setOnClickListener(this);
        cache_lin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_layout:
                finish();
                break;
            case R.id.notice_switcher_img:
                if (SPUtil.getBoolean("tongzhi_click", true)) {
                    SPUtil.putBoolean("tongzhi_click", false);
                    notice_switcher_img.setBackgroundResource(R.drawable.lk_setting_guan);
                    send();
                }else {
                    SPUtil.putBoolean("tongzhi_click", true);
                    notice_switcher_img.setBackgroundResource(R.drawable.lk_setting_kai);
                    send();
                }

                break;
            case R.id.answer_lin:
                if(ActivityUitl.isNetworkAvailable(mContext)){
                    Intent intent1 = new Intent();
                    intent1.putExtra("mHtmlUrl", APIProtocol.getRootURL() + "qa");
                    intent1.putExtra("title", getString(R.string.normal_qa));
                    intent1.setClass(mContext, WebViewActivity_Mess.class);
                    startActivity(intent1);
                }else{
                    ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                }
                break;
            case R.id.cache_lin:
                showCacheStatus(true);
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        FileUtil.deleteDir(bookCachePath.getPath());
                        clearBookSharedPreferences();
                        setCacheText();
                    }
                }.start();
                break;
            default:
                break;
        }
    }

    /**
     * 清除章节保存的SP信息
     */
    private void clearBookSharedPreferences() {
        //清除章节记录信息
        SharedPreferences sp = BasicApplication.getInstance().getSharedPreferences("laikan_sp", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        Map spMap = sp.getAll();
        Set set = spMap.keySet();
        for (Object aSet : set) {
            String hashKey = (String)aSet;
            if (!TextUtils.isEmpty(hashKey) &&
                (hashKey.contains("chaptep_rec")
                 || hashKey.contains("recCurPage")
                 || hashKey.contains("rewardNumberInt")
                 || hashKey.contains("_lastChapterId")
                 || hashKey.contains("chap_count_")
                 || hashKey.contains("chap_pos_")
                 || hashKey.contains("chapterCount_pos_")
                 || hashKey.contains("chapid_")
                 || hashKey.contains("isDowning_chapter")
                 || hashKey.contains("isDowning_chapter")
                 || hashKey.contains("buyback"))) {
                editor.remove(hashKey);
            }
        }
        editor.commit();
    }

    private void showCacheStatus(boolean isClearCache) {
        if (isClearCache) {
            tv_book_cache.setVisibility(View.GONE);
            iv_clearcache_loading.setVisibility(View.VISIBLE);
            mClearCacheAnimationDrawable.start();
        }else {
            mClearCacheAnimationDrawable.stop();
            iv_clearcache_loading.setVisibility(View.GONE);
            tv_book_cache.setVisibility(View.VISIBLE);
        }
    }

    private void send() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("sd", SPUtil.getString("token", ""));

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                try {
                    JSONObject obj = new JSONObject(httpResponse.responseContent);
                    String result = obj.getString("result");
                    if (Constants.RESULT_OK.equals(result)) {

                    }
                }catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {

            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_notify_receive + SPUtil.getBoolean("tongzhi_click", false));
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_notify_receive + SPUtil.getBoolean("tongzhi_click", false), map, null, null, requestListener);
    }
}
